<?php

class Pipes_CommandLine_ArgumentParser
{
	const PATTERN_WITH = '/--with=?(.*)/';

	private $_schema = array();

	public function __construct(array $schema) {
		$this->_schema = $schema;
	}

	public function parse($args) {
		$return = array();
		foreach ($this->_schema as $key => $value)
		{
			switch ($value['type']) {
				case 'bool' :
					$return[$value['name']] = in_array($key, $args);
					break;

				case 'array' :
					$inPattern = false;
					$cursor = -1;
					foreach ($args as $argValue) {
						if ($inPattern) {
							if ($argValue[0] == '-') {
								$inPattern = false;
							} else {
								if (!empty($return[$value['name']][$cursor])) {
									$return[$value['name']][$cursor] .= ' ';
								}
								$return[$value['name']][$cursor] .= $argValue;
							}
						}
						if (preg_match($value['pattern'], $argValue, $matches)) {
							$inPattern = true;
							$cursor++;
							if (!empty($matches[1])) {
								$return[$value['name']][$cursor] = $matches[1];
							}
						}
					}
					break;
			}
		}

		return $return;
	}
}
